<template>
  <Modal v-model="setModal" width="1100" @on-visible-change="closeMoad">
    <Form :model="formCity" :label-width="150" v-show="supplyPriceType == '1'">
      <FormItem label="默认参照城市设置">
        <Row>
          <Col span="4"
            ><Select v-model="formCity.templateDefaultCityUuid" @on-change="handleSelectDefaultReferCity">
              <Option
                v-for="(item, ki) in newCanZhaoDefault"
                :value="item.cityCode"
                :key="ki"
              >
                {{ item.cityName }}
              </Option>
            </Select></Col
          >
        </Row>
      </FormItem>
    </Form>
    <Form
      :model="formInline"
      ref="formInline"
      :label-width="150"
      :inline="true"
    >
      <FormItem label="选择供货城市:" :label-width="120">
        <Button type="primary" @click="handleCheckAll">全选</Button>
      </FormItem>
      <FormItem label="批量输入成本比例">
        <InputNumber :min="0.01" v-model="formInline.lossRatios"></InputNumber>
      </FormItem>
      <FormItem v-if="supplyPriceType != '1'" label="批量设置参照城市">
        <Select v-model="formInline.select" style="width: 100px" transfer>
          <Option
            v-for="(item, ki) in canZhao"
            :disabled="item.disabled"
            :value="item.cityCode"
            :key="item.cityCode + ki"
          >
            {{ item.cityName }}
          </Option>
        </Select>
      </FormItem>
      <Button type="primary" @click="handleBatch">确定</Button>
    </Form>
    <div class="radioMore">
      <CheckboxGroup v-model="checkAllCity" @on-change="selectGCity">
        <Checkbox
          v-for="item in groupCheckList"
          :key="item.cityCode"
          :disabled="cdisabled"
          :label="item.cityCode"
        >
          {{ item.cityName }}
        </Checkbox>
      </CheckboxGroup>
    </div>

    <Table
      border
      ref="selection"
      height="500"
      @on-selection-change="handleSelectionChange"
      :columns="newColumns"
      :data="dataSouce"
    >
    </Table>
    <div slot="footer">
      <Button @click="submitXiaoshouCity('no')">取消</Button>
      <Button type="primary" v-preventReClick @click="submitXiaoshouCity('ok')"
        >确认</Button
      >
    </div>
  </Modal>
</template>

<script>
import { ApiRequest } from '@api/basePage';
import { getCityNamesByPurchaseIneligibleRatio } from '@/utils/getUtils';

export default {
  name: 'index',
  data () {
    return {
      tableData: [],
      setCityDialog: true,
      formCity: {
        templateDefaultCityUuid: ''
      },
      checkAllCity: [],
      formInline: {
        lossRatios: null,
        select: ''
      },
      newColumns: [],
      newCanZhaoDefault: [],
      selectList: [] // 组件内表格勾选数据
    };
  },
  props: {
    canZhao: { type: Array }, // 表格下拉框数据
    canZhaoDefault: { type: Array }, // 统一区域左上角默认城市下拉框数据
    Columns: { type: Array }, // 表头数据
    dataSouce: { type: Array }, // 表格渲染数据
    groupCheckList: { type: Array }, // 多选框渲染数据
    quyuSku: { type: Array },
    supplyPriceType: { type: String }, // 判断统一还是区域
    supplyUuid: { type: String }, // 判断统一还是区域
    setModal: { type: Boolean, default: false }, // 弹框状态
    cdisabled: { type: Boolean, default: true },
    templateDefaultCityUuid: { type: String, default: '' } // 默认城市数据，该值为爷爷级传递，中间有隔了一层，本组件使用暂存调用。
  },
  created () {},
  mounted () {
    sessionStorage.setItem(
      'templateDefaultCityUuid',
      this.templateDefaultCityUuid
    );
    this.newColumns = this.Columns.map(item => {
      if (item.type == 'Select') {
        item.render = (h, { row, index }) => {
          if (this.supplyPriceType == '1') {
            // 如果该城市属于供货状态，且为统一区域，则直接赋值
            return <span>{row.templateCityName}</span>;
          } else {
            return h(
              'Select',
              {
                props: {
                  value: row.templateCityUuid,
                  transfer: true
                },
                on: {
                  'on-select': event =>
                    this.selectDropDownCity(event, row, index)
                }
              },
              this.canZhao.map(item => {
                return h('Option', {
                  props: {
                    disabled: item.disabled,
                    value: item.cityCode,
                    label: item.cityName
                  }
                });
              })
            );
          }
        };
      }
      if (item.type == 'inputJin') {
        item.render = (h, { row, index }) => {
          if (this.supplyPriceType == '1') {
            // 如果该值为通知，则直接将该输入康变为固定值，不再变化
            return <span>无需维护</span>;
          } else if (
            row.isSupply == '1' &&
            row.cityCode == row.templateCityUuid
          ) {
            // 判断是否供货，并且判断下拉供货城市是否与销售城市一致
            return <span>无需维护</span>;
          } else {
            return h('InputNumber', {
              props: {
                value: row[item.key],
              },
              on: {
                'on-change': event => this.onChangeRow(event, index, item.key)
              }
            });
          }
        };
      }
      if (item.type == 'input') {
        item.render = (h, { row, index }) => {
          if (row._disabled && row.cityCode == row.templateCityUuid) {
            // 当该输入框为disabled时，直接赋值，不展现输入框
            return <span>无需维护</span>;
          } else if (
            row.isSupply == '1' &&
            row.cityCode == row.templateCityUuid
          ) {
            // 判断是否供货，并且判断下拉供货城市是否与销售城市一致
            return <span>无需维护</span>;
          } else {
            return h('InputNumber', {
              props: {
                value: row[item.key],
              },
              on: {
                'on-change': event => this.onChangeRow(event, index, item.key)
              }
            });
          }
        };
      }
      return item;
    });
    this.newCanZhaoDefault = this.canZhaoDefault;
  },
  watch: {
    groupCheckList: function (newVal, oldVal) {
      let cityCodeList = newVal.map(item => {
        if (item.cityCode) {
          return item.cityCode
        }
      });
      this.checkAllCity = cityCodeList;
      this.selectGCity();
    },
    canZhao: function (newVal, oldVal) {
      this.canZhao = newVal;
    },
    dataSouce: function (newVal, oldVal) {
      this.dataSouce = newVal;
    },
    supplyUuid: function (newVal, oldVal) {
      this.supplyUuid = newVal;
    },
    setModal: function (newVal, oldVal) {
      if (newVal) {
        // 当弹框发生变化时。改变默认值城市值
        this.formCity.templateDefaultCityUuid = sessionStorage.getItem(
          'templateDefaultCityUuid'
        );
      } else {
        this.formCity.templateDefaultCityUuid = '';
        this.formInline = { lossRatios: null, select: '' };
      }
    }
  },
  methods: {
    // 选择默认参照
    handleSelectDefaultReferCity () {
      const cityInfo = this.newCanZhaoDefault.find(item => item.cityCode == this.formCity.templateDefaultCityUuid)
      this.dataSouce.forEach(item => {
        item.templateCityName = cityInfo?.cityName
        item.templateCityUuid = cityInfo?.cityCode
        const isUniqPurchase = this.supplyPriceType == '1' // 统一进价
        const isReferSelf = item.saleCityNo == item.templateCityUuid // 自己参照自己
        item._disabled = isUniqPurchase && isReferSelf
      })
    },
    onChangeRow (event, index, key) {
      this.dataSouce[index][key] = event;
    },
    // 弹框关闭时间需调用一下关闭事件。清除状态
    closeMoad (e) {
      if (!e) this.submitXiaoshouCity('no');
    },
    handleCheckAll () {
      let cityCodeList = this.groupCheckList.map(item => item.cityCode); // 全选时需要将所选择的城市传递
      this.checkAllCity = cityCodeList;
      this.$emit('selectGCity', this.checkAllCity, 0);
      this.selectGCity()
    },
    checkAlltrue () {
      this.$refs.selection.selectAll(true);
    },
    // -------------------     子组件事件抛出，提供给父组件调用
    emply () {
      this.$refs.selection.selectAll(false);
    },
    defaultCity () {
      this.$emit('defaultCity', this.formCity.templateDefaultCityUuid);
    },
    // ------------------------
    handleSelectionChange (data) {
      this.selectList = data;
      this.$emit('handleSelectionChange', data);
    },

    selectGCity () {
      this.formCity.templateDefaultCityUuid = '' // 清空默认参照
      var that = this;
      // 当勾选城市时，已经取消的城市，批量下拉已经勾选，则需要清空批量下拉，防止提交错误
      if (this.formInline.select) {
        let test = this.checkAllCity.some(
          item => item == this.formInline.select
        );
        if (!test) this.formInline.select = '';
      }
      this.canZhao.forEach(item => {
        item.disabled = true;
        this.checkAllCity.forEach(t => {
          if (t === item.cityCode) item.disabled = false;
        });
      });
      let selectgroupCheckList = this.groupCheckList.filter(item => {
        // 供货城市勾选框数据
        return this.checkAllCity.some(v => v == item.cityCode);
      });
      this.newCanZhaoDefault = this.canZhao.filter(item => {
        return this.checkAllCity.some(v => v == item.cityCode);
      });
      const { select, lossRatios } = this.formInline;
      this.dataSouce.forEach((item, index) => {
        if (!select && !lossRatios) {
          // 防止已经批量操作， 当两个值为空的时候，正常操作。
          item._disabled = false;
          item.isSupply = '2';
          const cityInfo = this.newCanZhaoDefault.find(item => item.cityCode == this.templateDefaultCityUuid)
          // 统一表单数据
          selectgroupCheckList.forEach(function (em, ex) {
            if (item.saleCityNo == em.cityCode) {
              item.isSupply = '1';
              item.templateCityName = cityInfo?.cityName;
              item.templateCityUuid = cityInfo?.cityCode;
              item.buyPriceRatio = 1;
              item.costPriceRatio = 1;
              // 如果相等的话就把表格禁用
              const isUniqPurchase = that.supplyPriceType == '1' // 统一进价
              const isReferSelf = item.saleCityNo == item.templateCityUuid // 自己参照自己
              if (isUniqPurchase && isReferSelf) {
                item._disabled = true // 禁用勾选
              }
              // if (
              //   (item.saleCityNo == item.templateCityUuid) &&
              //   that.supplyPriceType == '1'
              // ) {
              //   item._disabled = true;
              // }
            }
          });
        }
        this.canZhao.forEach(ele => {
          if (
            item.isSupply !== '1' &&
            ele.disabled &&
            item.templateCityUuid == ele.cityCode
          ) {
            item.templateCityUuid = '';
          }
        });
      });
    },
    handleBatch () {
      if (this.selectList.length == 0) {
        // 判断本地勾选数据
        return this.$Message.warning('请勾选列表哦');
      }
      const { lossRatios, select } = this.formInline;
      let giveData = { formInline: this.formInline, newDataSouce: [] }; // 声明回传函数

      let val = this.canZhao.find(item => item.cityCode === select);
      let cityName = val ? val.cityName : '';
      let uuidList = this.selectList.map(item => item.saleCityNo); // 提取选中数据的 唯一主键 uuid
      let checkList = this.selectList.filter(item => item.isSupply !== '1'); // 因供货条件为 是 的数据不需要调用接口，提取所有否的数据
      if (!lossRatios && checkList.length > 0) {
        // 当批量值与勾选框的值不为空时，调用接口赋值
        let params = checkList.map(item => ({
          saleCityUuid: item.saleCityNo,
          templateCityUuid: select
        }));
        ApiRequest(
          '/sysback/supplyinfopriceratio/getPriceRatioByAreaCode',
          'post',
          params
        ).then(res => {
          if (res.retStatus == '1') {
            giveData.newDataSouce = this.dataSouce.map(item => {
              if (uuidList.includes(item.saleCityNo)) {
                res.retData.forEach(v => {
                  if (item.saleCityNo == v.saleCityUuid) {
                    item.costPriceRatio = v.costPriceRatio;
                  }
                });
                if (this.supplyPriceType != '1') {
                  item.templateCity = cityName;
                  item.templateCityName = cityName;
                  item.templateCityUuid = select;
                }
              }
              return item;
            });
            this.$emit('handleBatch', giveData); // 因存在异步问题，将函数写到判断回调中
            this.emply();
          }
        });
      } else {
        giveData.newDataSouce = this.dataSouce.map(item => {
          if (uuidList.includes(item.saleCityNo)) {
            if (item._disabled) return
            item.costPriceRatio = lossRatios || 1;
            if (this.supplyPriceType != '1') {
              item.templateCity = cityName;
              item.templateCityName = cityName; // 批量操作时返回的数据也需显示
              item.templateCityUuid = select;
            }
          }
          return item;
        });
        // 将输入框数据 与新改变的表格数据重新返回到父组件， 并清空表格勾选
        this.$emit('handleBatch', giveData);
        this.emply();
      }
    },
    selectDropDownCity (e, row, index) {
      let params = [
        { saleCityUuid: row.saleCityNo, templateCityUuid: e.value }
      ];
      if (row.isSupply !== '1') {
        ApiRequest(
          '/sysback/supplyinfopriceratio/getPriceRatioByAreaCode',
          'post',
          params
        ).then(res => {
          if (res.retStatus == '1') {
            row.costPriceRatio = res.retData[0].costPriceRatio;
          }
        });
      }
      let sIndex = this.canZhao.findIndex(item => item.cityCode == e.value);
      row.templateCityName = this.canZhao[sIndex].cityName;
      row.templateCityUuid = this.canZhao[sIndex].cityCode;
      row.templateCitySaleAreaNo = this.canZhao[sIndex].templateCitySaleAreaNo;
      row.templateCitySaleAreaName = this.canZhao[sIndex].templateCitySaleAreaName;
      this.dataSouce[index] = row;

      this.$emit('selectDropDownCity', this.dataSouce);
    },

    // 设置参照城市-提交
    submitXiaoshouCity (name) {
      if (name === 'no') {
        return this.$emit('ChangeSetModal', false);
      }
      this.dataSouce.forEach(item => {
        if (item.saleCityNo === item.templateCityUuid) { // 当前是无需参照
          item.buyPriceRatio = 1;
          item.costPriceRatio = 1;
        }
      });
      const warnMsgs = getCityNamesByPurchaseIneligibleRatio(this.dataSouce);
      if (warnMsgs) { return this.$message.warning(`${warnMsgs}：进价比例和成本价比例均需在0.6-5之间`); }
      if (this.supplyPriceType == '1' && !this.formCity.templateDefaultCityUuid) {
        return this.$Message.warning('请设置默认参照城市');
      }
      // 参照城市第一层弹框展示数据
      let submitReferenceCityList = [];
      // 区域进价表格数据
      let unarr = [];
      let obj = {};
      submitReferenceCityList = this.dataSouce.map((item) => {
        this.quyuSku.forEach((sk) => {
          obj = {
            isMainSupply: '1',
            isSupply: item.isSupply,
            mainUnitStr: sk.mainUnitStr,
            supplyUuid: this.supplyUuid,
            productUuid: item.productUuid,
            saleProvinceUuid: item.provinceCode,
            saleProvinceName: item.provinceName,
            saleCityUuid: item.saleCityNo,
            saleCityName: item.saleCityName,
            saleAreaUuid: item.areaCode,
            saleAreaName: item.areaName,
            templateCityUuid: item.templateCityUuid,
            templateCityName: item.templateCityName ? item.templateCityName : item.templateCity,
            buyPriceRatio: item.isSupply === '1' && item.saleCityNo === item.templateCityUuid ? 1 : item.buyPriceRatio,
            costPriceRatio: item.isSupply === '1' && item.saleCityNo === item.templateCityUuid ? 1 : item.costPriceRatio,
            templateCitySaleAreaNo: item.templateCitySaleAreaNo,
            templateCitySaleAreaName: item.templateCitySaleAreaName
          };
        });
        return obj;
      });

      // 校验是否存在未选择参照城市项
      const hasEmptySelect = submitReferenceCityList.some(item => !item.templateCityUuid);
      if (hasEmptySelect) {
        return this.$Message.warning('请填写完整参照城市');
      }

      // 被关联的 不能参照别人
      let isReferenceError = false;
      submitReferenceCityList.forEach(item => {
        if (item.saleCityUuid != item.templateCityUuid) {
          submitReferenceCityList.forEach(ele => {
            if (ele.saleCityUuid == item.templateCityUuid) {
              if (ele.saleCityUuid !== ele.templateCityUuid) {
                isReferenceError = true;
              }
            }
          });
        }
      });
      if (isReferenceError) {
        return this.$Message.error('参照城市之间不能互相参照');
      }
      let templateModal = false; // 第一层Modal 状态
      this.defaultCity(); // 先调用默认城市函数， 传递值。否则会直接清空
      // 如果为 区域供价 组合供价信息
      if (this.supplyPriceType == '2') {
        // 过滤参照城市与销售城市相同的销售城市列表,用于与sku交叉生成进价列表
        let saleCityList = submitReferenceCityList.reduce((value, item) => {
          if (item.saleCityUuid === item.templateCityUuid) {
            value.push({
              templateCityName: item.templateCityName,
              templateCityUuid: item.templateCityUuid,
              saleAreaName: item.saleAreaName,
              saleAreaUuid: item.saleAreaUuid,
              saleCityName: item.saleCityName,
              saleCityUuid: item.saleCityUuid,
              templateCitySaleAreaNo: item.templateCitySaleAreaNo,
              templateCitySaleAreaName: item.templateCitySaleAreaName
            });
          }
          return value;
        }, []);
        // 销售城市与sku交叉遍历生成区域进价列表
        let areaEnterPriceList = [];
        saleCityList.forEach((item) => {
          this.quyuSku.forEach(function (ele) {
            let obj = {
              templateCityName: item.templateCityName,
              templateCityUuid: item.templateCityUuid,
              saleAreaName: item.saleAreaName,
              templateCitySaleAreaNo: item.templateCitySaleAreaNo,
              templateCitySaleAreaName: item.templateCitySaleAreaName,
              saleAreaUuid: item.saleAreaUuid,
              purchaseUnitStr: ele.purchaseUnitStr,
              specDetailStr: ele.specDetailStr,
              supplyGoodsUnit: ele.purchaseUnitStr,
              unitName: ele.unitName,
              mainUnitStr: ele.mainUnitStr,
              addPriceType: ele.addPriceType,
              skuNo: ele.skuNo,
              supplyProductInfo: {
                unitName: ele.unitName,
                specDetailStr: ele.specDetailStr,
                supplyGoodsUnit: ele.purchaseUnitStr
              }
            };
            areaEnterPriceList.push(obj);
          });
        });
        areaEnterPriceList.forEach((item) => {
          if (JSON.stringify(unarr).indexOf(JSON.stringify(item)) === -1) {
            item.purchasePriceType = '2';
            item.abnormalPurchaseConvertRatio = item.abnormalPurchaseConvertRatio || 0;
            item.theoryConvertRatio = item.theoryConvertRatio || 0;
            item.actualConvertRatio = item.actualConvertRatio || 0;
            item.rebateRatio = item.rebateRatio || 0;
            item.processChargesRatio = item.processChargesRatio || 0;
            item.packRatio = item.packRatio || 0;
            item.freightRatio = item.freightRatio || 0;
            item.purchasePrice = item.purchasePrice || 0;
            // item.factoryFacePrice = item.factoryFacePrice || 0;
            unarr.push(item);
          }
        });
      }
      this.$emit('submitXiaoshouCity', {
        submitReferenceCityList,
        templateModal,
        unarr
      });
      this.$Message.success('提交成功');
      this.$emit('ChangeSetModal', false);
    }
  }
};
</script>

<style scoped>
.radioMore {
  padding: 0px 20px 20px 20px;
}
</style>
